'use client';

import React, { useState, useEffect, createContext, useContext } from 'react';
import { useCollaboration } from '@/hooks/use-collaboration';
import { useSocket } from '@/hooks/use-socket';
import { ResizablePanel, ResizablePanelGroup, ResizableHandle } from '@/components/ui/resizable';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { CollaborationInfoPanel } from '@/components/project/collaboration-info-panel';
import { DocumentHistory } from '@/components/project/document-history';
import { DocumentComments } from '@/components/project/document-comments';
import { DocumentSuggestions } from '@/components/project/document-suggestions';
import { Separator } from '@/components/ui/separator';
import { MessageSquare, History, LightbulbIcon, Info, RefreshCw, Wifi, WifiOff } from 'lucide-react';
import { CollaborationProvider } from '@/hooks/use-collaboration';
import { toast } from '@/components/ui/use-toast';
import { Button } from '@/components/ui/button';
import { AlertCircle } from 'lucide-react';
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";

// 创建全局Socket上下文
const GlobalSocketContext = createContext<{
  isSocketReady: boolean;
  reconnectSocket: () => void;
  isLocalMode: boolean;
  enableLocalMode: () => void;
}>({
  isSocketReady: false,
  reconnectSocket: () => {},
  isLocalMode: false,
  enableLocalMode: () => {}
});

export const useGlobalSocket = () => useContext(GlobalSocketContext);

interface CollaborativeWorkspaceProps {
  projectId: string;
  documentId: string;
  children: React.ReactNode;
  className?: string;
}

export function CollaborativeWorkspace({ 
  projectId, 
  documentId, 
  children,
  className = '' 
}: CollaborativeWorkspaceProps) {
  const { isConnected, socket, connectionState, error, reconnect, inLocalMode, switchToLocalMode, on } = useSocket();
  const [activeTab, setActiveTab] = useState<string>('info');
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [isSocketReady, setIsSocketReady] = useState(false);
  const [isReconnecting, setIsReconnecting] = useState(false);
  const [errorDetails, setErrorDetails] = useState<{ type: string, message: string } | null>(null);
  
  // 根据窗口大小调整侧边栏
  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth < 768) {
        setSidebarCollapsed(true);
      } else {
        setSidebarCollapsed(false);
      }
    };
    
    handleResize();
    window.addEventListener('resize', handleResize);
    
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // 监听socket连接状态
  useEffect(() => {
    if (isConnected && socket) {
      console.log('协作工作区: Socket已连接');
      setIsSocketReady(true);
      setIsReconnecting(false);
      setErrorDetails(null);
      
      if (!inLocalMode) {
        // 显示连接成功通知
        toast({
          title: "协作连接已建立",
          description: "实时协作功能已准备就绪",
          duration: 3000,
        });
      } else {
        // 显示本地模式通知
        toast({
          title: "本地模式已启用",
          description: "您的更改将保存在本地，但不会同步到其他用户",
          duration: 5000,
        });
      }
    } else {
      setIsSocketReady(false);
      if (connectionState === 'disconnected') {
        console.log('协作工作区: Socket已断开');
        // 显示断开连接通知
        toast({
          title: "协作连接已断开",
          description: "正在尝试重新连接...",
          duration: 5000,
          variant: "destructive",
        });
      } else if (connectionState === 'error') {
        console.log('协作工作区: 连接错误', error);
        // 显示错误通知
        toast({
          title: "连接错误",
          description: error?.message || "服务器连接错误，请尝试刷新页面",
          duration: 8000,
          variant: "destructive",
        });
      }
    }
  }, [isConnected, socket, connectionState, error, inLocalMode]);

  // 监听连接错误
  useEffect(() => {
    // Check if socket and on function are available
    if (socket && typeof on === 'function') {
      const unsubErrorHandler = on('connection-error', (data) => {
        setErrorDetails(data);
        setIsReconnecting(false);
      });
      
      const unsubStatusHandler = on('connection-status', (data) => {
        if (data.status === 'local_mode') {
          toast({
            title: "已切换至本地模式",
            description: "您的更改将保存在本地，但不会同步到服务器",
            duration: 5000,
          });
        }
      });
      
      return () => {
        if (typeof unsubErrorHandler === 'function') unsubErrorHandler();
        if (typeof unsubStatusHandler === 'function') unsubStatusHandler();
      };
    }
    
    // Return empty cleanup function if no socket or on function
    return () => {};
  }, [socket, on]);

  // 手动重连
  const handleReconnect = () => {
    setIsReconnecting(true);
    setErrorDetails(null);
    toast({
      title: "正在重新连接",
      description: "尝试重新建立协作连接...",
      duration: 3000,
    });

    // 调用socket的reconnect方法
    if (reconnect) {
      reconnect();
      
      // 如果15秒后仍未连接，显示失败提示
      const timeout = setTimeout(() => {
        if (!isSocketReady) {
          setIsReconnecting(false);
          toast({
            title: "重连失败",
            description: "请尝试启用本地模式或刷新页面",
            duration: 5000,
            variant: "destructive",
          });
        }
      }, 15000);
      
      return () => clearTimeout(timeout);
    }
  };

  // 启用本地模式
  const handleEnableLocalMode = () => {
    if (switchToLocalMode) {
      switchToLocalMode();
      toast({
        title: "本地模式已启用",
        description: "您的更改将保存在本地，不会受到服务器问题影响",
        duration: 3000,
      });
    }
  };
  
  return (
    <CollaborationProvider projectId={projectId} documentId={documentId} className={className}>
      <GlobalSocketContext.Provider value={{ 
        isSocketReady, 
        reconnectSocket: handleReconnect,
        isLocalMode: inLocalMode,
        enableLocalMode: handleEnableLocalMode
      }}>
        <div className={`flex flex-col h-full`}>
          {/* 本地模式通知 */}
          {inLocalMode && (
            <Alert className="mb-4">
              <WifiOff className="h-4 w-4" />
              <AlertTitle>本地模式已启用</AlertTitle>
              <AlertDescription>
                您的更改将保存在本地，但不会同步到其他用户。
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={handleReconnect} 
                  className="ml-2"
                >
                  尝试重新连接
                </Button>
              </AlertDescription>
            </Alert>
          )}

          {/* 服务器错误通知 */}
          {errorDetails?.type === 'server_error' && !inLocalMode && (
            <Alert variant="destructive" className="mb-4">
              <AlertCircle className="h-4 w-4" />
              <AlertTitle>服务器错误</AlertTitle>
              <AlertDescription>
                无法连接到协作服务器，可能是临时性问题。您可以：
                <div className="flex mt-2 gap-2">
                  <Button 
                    variant="outline" 
                    size="sm" 
                    onClick={handleReconnect} 
                    disabled={isReconnecting}
                  >
                    <RefreshCw className={`h-4 w-4 mr-1 ${isReconnecting ? 'animate-spin' : ''}`} />
                    重试连接
                  </Button>
                  <Button 
                    variant="secondary" 
                    size="sm" 
                    onClick={handleEnableLocalMode}
                  >
                    <WifiOff className="h-4 w-4 mr-1" />
                    启用本地模式
                  </Button>
                </div>
              </AlertDescription>
            </Alert>
          )}

          <ResizablePanelGroup direction="horizontal" className="h-full">
            {/* 主编辑区域 */}
            <ResizablePanel defaultSize={70} minSize={40} className="h-full">
              {children}
            </ResizablePanel>
            
            {/* 分隔线和调整手柄 */}
            <ResizableHandle withHandle />
            
            {/* 协作侧边栏 */}
            <ResizablePanel 
              defaultSize={sidebarCollapsed ? 0 : 30} 
              minSize={20} 
              maxSize={40} 
              className="h-full" 
              collapsible={true} 
              collapsedSize={0}
              onCollapse={() => setSidebarCollapsed(true)}
              onExpand={() => setSidebarCollapsed(false)}
            >
              <Tabs value={activeTab} onValueChange={setActiveTab} className="h-full flex flex-col">
                <div className="border-b px-3 pt-3">
                  <TabsList className="w-full grid grid-cols-4">
                    <TabsTrigger value="info" title="协作信息">
                      <Info className="h-4 w-4" />
                    </TabsTrigger>
                    <TabsTrigger value="comments" title="评论">
                      <MessageSquare className="h-4 w-4" />
                    </TabsTrigger>
                    <TabsTrigger value="history" title="历史">
                      <History className="h-4 w-4" />
                    </TabsTrigger>
                    <TabsTrigger value="suggestions" title="建议">
                      <LightbulbIcon className="h-4 w-4" />
                    </TabsTrigger>
                  </TabsList>
                </div>
                
                <div className="flex-1 overflow-hidden">
                  <TabsContent value="info" className="h-full p-3 pt-0 m-0">
                    <div className="mb-3">
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-2">
                          {isSocketReady ? (
                            inLocalMode ? (
                              <div className="text-amber-500 flex items-center">
                                <WifiOff className="h-4 w-4 mr-1" />
                                <span>本地模式</span>
                              </div>
                            ) : (
                              <div className="text-green-500 flex items-center">
                                <Wifi className="h-4 w-4 mr-1" />
                                <span>在线</span>
                              </div>
                            )
                          ) : (
                            <div className="text-red-500 flex items-center">
                              <AlertCircle className="h-4 w-4 mr-1" />
                              <span>{connectionState === 'error' ? '连接错误' : '已断开'}</span>
                            </div>
                          )}
                        </div>
                        {!isSocketReady && (
                          <Button 
                            size="sm" 
                            variant="ghost"
                            onClick={handleReconnect}
                            disabled={isReconnecting || inLocalMode}
                          >
                            <RefreshCw className={`h-4 w-4 mr-1 ${isReconnecting ? 'animate-spin' : ''}`} />
                            重试
                          </Button>
                        )}
                        {connectionState === 'error' && !inLocalMode && (
                          <Button 
                            size="sm" 
                            variant="outline"
                            onClick={handleEnableLocalMode}
                          >
                            <WifiOff className="h-4 w-4 mr-1" />
                            本地模式
                          </Button>
                        )}
                      </div>
                    </div>
                    <Separator className="my-2" />
                    <CollaborationInfoPanel 
                      projectId={projectId}
                      documentId={documentId}
                      className="h-full"
                    />
                  </TabsContent>
                  
                  <TabsContent value="comments" className="h-full p-3 pt-0 m-0">
                    <DocumentComments
                      projectId={projectId}
                      documentId={documentId}
                      className="h-full"
                    />
                  </TabsContent>
                  
                  <TabsContent value="history" className="h-full p-3 pt-0 m-0">
                    <DocumentHistory
                      projectId={projectId}
                      documentId={documentId}
                      className="h-full"
                    />
                  </TabsContent>
                  
                  <TabsContent value="suggestions" className="h-full p-3 pt-0 m-0">
                    <DocumentSuggestions
                      projectId={projectId}
                      documentId={documentId}
                      className="h-full"
                    />
                  </TabsContent>
                </div>
              </Tabs>
            </ResizablePanel>
          </ResizablePanelGroup>
          
          {/* 断开连接提示和重连按钮 */}
          {!isSocketReady && !inLocalMode && (
            <div className="fixed bottom-4 right-4 bg-destructive text-destructive-foreground px-4 py-3 rounded-md shadow-lg z-50 flex items-center gap-3">
              <span>协作连接已断开，正在重新连接...</span>
              <Button 
                size="sm" 
                variant="outline"
                className="whitespace-nowrap"
                onClick={handleReconnect}
                disabled={isReconnecting}
              >
                <RefreshCw className={`h-4 w-4 mr-1 ${isReconnecting ? 'animate-spin' : ''}`} />
                {isReconnecting ? '连接中...' : '立即重连'}
              </Button>
            </div>
          )}
        </div>
      </GlobalSocketContext.Provider>
    </CollaborationProvider>
  );
} 